package xiaoa.java.utils;

import java.io.File;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.FileUtils;

/**
 * http请求工具
 * 
 * @author lkc
 * @date 2017年3月31日 下午5:09:28
 * @version V1.0
 *
 */
public class HttpUtils {

	/**
	 * 
	 * 初始化请求handler
	 */
	private static void initRequestHeader(HttpMethod method) {

		// 设置为短链
		method.setRequestHeader("Connection", "close");
		method.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8");
		method.setRequestHeader("Accept-Encoding", "deflate, sdch");
		method.setRequestHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
		method.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
	}

	/**
	 * 发送一个post请求
	 * 
	 * @Title: doPost
	 * @param url
	 * @param paramsMap
	 * @return
	 * @throws Throwable
	 * @author xiaoa
	 */
	public static ResponseResult doPost(String url, Map<String, String> paramsMap, Integer socketTimeOut, Integer connTimeOut , Map<String, String> handMap)
			throws Exception {

		if (url == null || url.trim().equals("")) {
			throw new RuntimeException("参数有误");
		}

		// 创建一个请求方法
		PostMethod method = new PostMethod(url);

		if (paramsMap != null && paramsMap.size() > 0) {
			for (String key : paramsMap.keySet()) {
				method.setParameter(key, paramsMap.get(key));
			}
		}

		return doRequest(method, socketTimeOut, connTimeOut , handMap);
	}

	/**
	 * 发送http表单请求
	 * 
	 * @Title: doPost
	 * @param url
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 * @author lkc
	 */
	public static ResponseResult doPost(String url, Map<String, String> paramsMap) throws Exception {

		return doPost(url, paramsMap, null, null , null);
	}

	/**
	 * 发送get请求
	 * 
	 * @Title: doGet
	 * @param url
	 * @param paramsMap
	 * @param transactionId
	 * @return
	 * @throws Exception
	 * @author lkc
	 */
	public static ResponseResult doGet(String url, Integer socketTimeOut, Integer connTimeOut , Map<String, String> handMap) throws Exception {

		if (url == null || url.trim().equals("")) {
			throw new RuntimeException("参数有误");
		}

		// 创建一个请求方法
		GetMethod method = new GetMethod(url);

		return doRequest(method, socketTimeOut, connTimeOut,handMap);
	}

	/**
	 * 发送get请求
	 * 
	 * @Title: doGet
	 * @param url
	 * @return
	 * @throws Exception
	 * @author lkc
	 */
	public static ResponseResult doGet(String url) throws Exception {
		return doGet(url, null, null,null);
	}

	/**
	 * 进行请求
	 * 
	 * @Title: doRequest
	 * @param method
	 * @return
	 * @author lkc
	 */
	private static ResponseResult doRequest(HttpMethod method, Integer socketTimeOut, Integer connTimeOut ,Map<String, String>  handMap) throws Exception {

		if (method == null) {
			throw new RuntimeException(" method is null");
		}

		// 创建一个请求对象
		HttpClient client = new HttpClient();

		ResponseResult reponseBody = new ResponseResult();

		
		try {

			// 默认超时时间 5分钟
			if (socketTimeOut == null || socketTimeOut <= 0) {
				socketTimeOut = (int) TimeUnit.MINUTES.toMillis(5);
			}

			// 默认连接超时时间 1 分钟
			if (connTimeOut == null || connTimeOut <= 0) {
				connTimeOut = (int) TimeUnit.MINUTES.toMillis(1);
			}

			initRequestHeader(method);
			client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, true));
			client.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
			client.getParams().setIntParameter("http.socket.timeout", socketTimeOut);
			client.getParams().setIntParameter("http.connection.timeout", connTimeOut);

			initRequestHeader(method);
			
			if (handMap != null && handMap.size() > 0){
				
				handMap.forEach((k , v)-> method.setRequestHeader(k, v));
			}

			// 发送请求
			int status = client.executeMethod(method);

			reponseBody.setCode(status);
			reponseBody.setBody(method.getResponseBody());

		} finally {
			if (method != null) {
				method.abort();
			}
		}

		return reponseBody;
	}

	/**
	 * 发送post请求
	 * 
	 * @Title: doPost
	 * @param url
	 * @param text
	 * @param coding
	 * @param socketTimeOut
	 * @param connTimeOut
	 * @return
	 * @throws Exception
	 * @author lkc
	 */
	public static ResponseResult doPost(String url, String text, String coding, Integer socketTimeOut, Integer connTimeOut , Map<String, String> handMap)
			throws Exception {

		if (url == null || url.trim().equals("")) {
			throw new RuntimeException("参数有误");
		}

		// 创建一个请求方法
		PostMethod method = new PostMethod(url);

		if (text != null) {
			method.setRequestEntity(new StringRequestEntity(text, "text/plain", coding));
		}

		return doRequest(method, socketTimeOut, connTimeOut,handMap);
	}

	/**
	 * 发送post请求
	 * 
	 * @Title: doPost
	 * @param url
	 * @param text
	 * @param coding
	 * @return
	 * @throws Exception
	 * @author lkc
	 */
	public static ResponseResult doPost(String url, String text, String coding) throws Exception {
		return doPost(url, text, coding, null, null,null);
	}
	
	
	/**
	 * 返回结果
	 * @author xiaoa
	 * @date 2018年1月6日 上午9:46:54
	 * @version V1.0
	 *
	 */
	public static class ResponseResult{
		
		private byte[] body;
		
		private int code;

		public byte[] getBody() {
			return body;
		}

		public void setBody(byte[] body) {
			this.body = body;
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}
		
		
		
		public String asString(){
			if (body != null){
				return new String(body);
			}
			return null;
		}
		
		
	}
	
	
	public static void main(String[] args)throws Throwable {
		
		ResponseResult body = doGet("http://img5.imgtn.bdimg.com/it/u=1119515502,3748467009&fm=27&gp=0.jpg");
		

		FileUtils.writeByteArrayToFile(new File("e://图片/my.jpg"), body.getBody());

//		System.out.println(body);
		
		 String base64 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(body.getBody()));
		
		

		
		System.out.println("<img class='main_img img-hover' src='" + base64 + "' style='background-color: rgb(175, 154, 178); width: 150px; height: 218px;'>");
		
	}

}
